package com.jn.exam.listener;

import com.jn.exam.JwtUtils;
import com.jn.exam.exceptionHandler.ExamException;
import com.jn.exam.exceptionHandler.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * @author 江南大学1033190417
 * @date 2022/1/21 22:24
 */
@Slf4j
public class RequestInterceptor extends HandlerInterceptorAdapter {

    /**
     * 进入controller层之前拦截请求
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isEffective = JwtUtils.checkToken(request);//验证token
        if (isEffective) {
            return true;
        } else {
            System.out.println("***url:"+request.getRequestURI());
            log.info("主机{}的端口{}视图通过非法token访问资源{}",request.getRemoteAddr(),request.getRemotePort(),request.getRequestURI());
            throw new ExamException(999,"请登录");
        }
    }
}
